package com.engine.cn.service.impl;

import com.engine.cn.service.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class InventoryServiceImpl implements InventoryService {
    //不满足分布式锁的要求，高并发情况下必然出现超卖现象
    private final Lock lock = new ReentrantLock();

    @Value("${server.port}")
    private String port;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String sale() {
        String message;
        lock.lock();
        try {
            //查询订单消息
            String result = redisTemplate.opsForValue().get("inventory001");
            //判断库存是否足够
            int inventoryNumber = Objects.isNull(result) ? 0 : Integer.parseInt(result);
            //减库存
            if (inventoryNumber > 0) {
                redisTemplate.opsForValue().set("inventory001", String.valueOf(--inventoryNumber));
                message = "成功卖出一个商品，剩余库存量" + (--inventoryNumber) + "端口号是：" + port;
                System.out.println(message);
            } else {
                message = "商品卖完了";
            }
        } finally {
            lock.unlock();
        }

        return message;
    }
}
